package com.keyou.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keyou.reggie.common.CustomException;
import com.keyou.reggie.entity.Category;
import com.keyou.reggie.entity.Dish;
import com.keyou.reggie.entity.SetMeal;
import com.keyou.reggie.mapper.CategoryMapper;
import com.keyou.reggie.service.CategoryService;
import com.keyou.reggie.service.DishService;
import com.keyou.reggie.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: klq
 * @Date: 2023/1/10 15:43
 * @Description:
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 根据id删除分类，删除之前需要进行判断
     *
     * @param categoryId
     */
    @Override
    public void removeCategory(Long categoryId) {

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, categoryId);
        //加返回值方便debug、日志打印
        long dishCount = dishService.count(dishLambdaQueryWrapper);
        log.info("dish查询条件，查询到的条目数为：{}", dishCount);
        if (dishCount > 0) {
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        LambdaQueryWrapper<SetMeal> setMealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setMealLambdaQueryWrapper.eq(SetMeal::getCategoryId, categoryId);
        long setMealCount = setMealService.count(setMealLambdaQueryWrapper);
        log.info("setmeal查询条件，查询到的条目数为：{}", setMealCount);
        if (setMealCount > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }

        //正常删除
        this.removeById(categoryId);
    }
}